package com.top10.controller;


import com.top10.bean.JwtUtil;
import com.top10.bean.ResponseBean;
import com.top10.common.WebConst;
import com.top10.entity.UserOpenid;
import com.top10.service.IUserOpenidService;
import com.top10.utils.MD5;
import com.top10.utils.QQUtil;
import com.top10.utils.RandomUtils;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;


@RestController
@RequestMapping("/qq")
public class QqLoginController {

	@Value("${jwt.period}")
	private Long period;//token有效时间（毫秒）
	@Value(("${jwt.issuer}"))
	private String issuer;//jwt token 签发人
	@Autowired
	private JwtUtil jwtUtil;
    @Autowired
	private IUserOpenidService iUserOpenidService;

	@RequestMapping("/login")
	public ResponseBean qqLogin(String access_token,String openid,HttpServletResponse response)throws Exception{

	/*	UserOpenid userOpenid=iUserOpenidService.selectOne(new EntityWrapper<UserOpenid>().eq("qq_openid",openid));
        if (userOpenid==null){
        	return ResponseBean.createSuccess("还没注册用户,请先注册");
		}*/
		//获取用户微信信息
		Map<String, String> userInfoMap = QQUtil.getUserInfo(access_token, openid);
		String ret=userInfoMap.get("ret");
		Integer i = null;
		if(ret!=null) {
			i = Integer.valueOf(ret);
		}
			if(i!=0){
			return ResponseBean.createError("QQ授权失败");
		}
         UserOpenid openid1 = new UserOpenid();
		 openid1.setQqOpenid(openid);
 		 String uuid =RandomUtils.makeUUID();
         openid1.setUserUuid(uuid);
         iUserOpenidService.insert(openid1);
		// 制作JWT Token
		String jwtToken = jwtUtil.issueJWT(MD5.getRandomString(20),//令牌id
				uuid,//用户id
				(issuer == null ? JwtUtil.DEFAULT_ISSUER : issuer),//签发
				(period == null ? JwtUtil.DEFAULT_PERIOD : period),//token有效时间
				SignatureAlgorithm.HS512);
		//token存入 response里的Header
		response.setHeader(WebConst.TOKEN,jwtToken);
		return ResponseBean.createSuccess().setMessage("登录成功").addData("token",jwtToken).addData("userInfoMap",userInfoMap);
	}
}
